package com.xhdx.es.adau.util;

import java.io.Serializable;

/**
 * @description 公共返回定义
 *
 * @param <T>
 *            返回对象
 */
public class BaseRespone<T> implements Serializable, Cloneable {
    public static final long serialVersionUID = 1L;
    private static final int SUCCESS_CODE = 200;
    public static final int FAIL_CODE = 500;
    public static final int TOKEN_ERROR_CODE = 40101;
    public static final int TOKEN_FORBIDDEN_CODE = 40301;
    public static final BaseRespone<String> SUCCESS = new BaseRespone<String>(SUCCESS_CODE, null, null);
    public static final BaseRespone<String> FAIL = new BaseRespone<String>(FAIL_CODE, null, null);
    public static final BaseRespone<String> TOKEN_ERROR = new BaseRespone<String>(TOKEN_ERROR_CODE, "请重新登录", null);
    public static final BaseRespone<String> TOKEN_FORBIDDEN = new BaseRespone<String>(TOKEN_FORBIDDEN_CODE, "请重新登录",
            null);
    private int code;
    private String msg;
    private T content;

    private BaseRespone() {
    }

    private BaseRespone(int code, String msg, T content) {
        this.code = code;
        this.msg = msg;
        this.content = content;
    }

    public static <T> BaseRespone<T> getSuccessResponse(String msg) {
        return new BaseRespone<T>(SUCCESS_CODE, msg, null);
    }

    public static <T> BaseRespone<T> getResponse(int code) {
        return new BaseRespone<T>(code, null, null);
    }

    public static <T> BaseRespone<T> getResponse(int code, String msg) {
        return new BaseRespone<T>(code, msg, null);
    }

    public static <T> BaseRespone<T> getResponse(int code, String msg, T content) {
        return new BaseRespone<T>(code, msg, content);
    }

    public BaseRespone<T> code(int code) {
        try {
            @SuppressWarnings({ "unchecked" })
            BaseRespone<T> clone = (BaseRespone<T>) this.clone();
            clone.code = code;
            return clone;
        } catch (CloneNotSupportedException e) {
            throw Exceptions.unchecked(e);
        }
    }

    public BaseRespone<T> msg(String msg) {
        try {
            @SuppressWarnings({ "unchecked" })
            BaseRespone<T> clone = (BaseRespone<T>) this.clone();
            clone.msg = msg;
            return clone;
        } catch (CloneNotSupportedException e) {
            throw Exceptions.unchecked(e);
        }
    }

    public <S> BaseRespone<S> content(S content) {
        return new BaseRespone<S>(this.code, this.msg, content);
    }

    public int getCode() {
        return code;
    }

    public boolean isSuccess() {
        return code == 200 || new Integer(code).toString().startsWith("1");
    }

    public String getMsg() {
        return msg;
    }

    public T getContent() {
        return content;
    }

    @Override
    public String toString() {
        return "BaseRespone [success=" + isSuccess() + ", code=" + code + ", msg=" + msg + ", content=" + content + "]";
    }
}
